package com.alex.controller;


import common.beans.ResultBean;
import common.util.CacheUtil;
import common.util.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j

@RestController
@RequestMapping("login")
public class LoginController {

    @Resource
    HttpServletResponse response;

    @Resource
    HttpServletRequest request;


    @Resource
    CacheUtil cacheUtil;

    @GetMapping("loginout")
    public ResultBean<Object> loginout(HttpServletResponse response, HttpSession session) {
        //清除cookie 判断 如果是采用旧系统就还是原来的 如果是新的 需要请求下新系统的退出登录
        Map<String, Object> map = new HashMap<>();
        cookieExpire("userinfo");
        cookieExpire("tsguser");
        cacheUtil.clearUserCache();
        session.invalidate();
        //远程退出 user.tsgyun.com session里面的用户信息 看了猛哥代码 看出来的 2020年11月25日15:45:30
        //退出地址  https://user.tsgyun.com/user/logout
        String domain = IPUtil.getDomain(request);
        if (domain.equals("yuntsg.com")) {
            domain = "tsgyun.com";
        }
        map.put("flag", 1);
        map.put("url", "https://user.tsgyun.com/user/logout");
        return new ResultBean<>(map);
    }

    private void cookieExpire(String name) {
        String domain = IPUtil.getDomain(request);
//        String domain = StringUtil.getDomain(request);
        Cookie cookies = new Cookie(name, null);
        cookies.setPath("/");
        cookies.setDomain(domain);
        cookies.setMaxAge(0);
        response.addCookie(cookies);
    }

}
